<template>
  <el-container>
    <el-header>
      <span style="font-weight:bold; color:blue;">商品导入</span>
    </el-header>
    <el-upload
      class="upload-demo"
      ref="upload"
      action="http://test.skm.cnscoo.cc/web/v1/sku"
      headers.X-Auth-Token = "b3fd13f6-37e8-49d6-a297-51eb7dbebead"
      accept=".json"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :auto-upload="false"
      :before-upload="beforeAvatarUpload"
      style="margin-left:20px"
    >
      <el-button slot="trigger" size="medium" type="primary">选取文件</el-button>
      <el-button
        style="margin-left: 20px;"
        size="medium"
        type="success"
        @click="submitUpload"
      >上传到服务器</el-button>
      <div slot="tip" class="el-upload__tip">只能上传JSON文件，且不超过10MB</div>
    </el-upload>
  </el-container>
</template>

<script>
export default {
  data() {
    return {
      fileList: [
        {
          name: "package-lock.json",
          url:
            "../../../package-lock.json"
        },
        {
          name: "package.json",
          url:
            "../../../package.json"
        }
      ]
    };
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    beforeAvatarUpload(file) {
      var msg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = msg === "json";
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!extension) {
        this.$message({
          message: "上传文件只能是JSON格式!",
          type: "warning"
        });
      }
      if (!isLt2M) {
        this.$message({
          message: "上传文件大小不能超过 10MB!",
          type: "warning"
        });
      }
      return extension || isLt2M;
    }
  }
};
</script>